package com.example.service.impl;

import com.example.common.ServiceCode;
import com.example.common.ServiceException;
import com.example.dao.MessageMapper;
import com.example.entity.Message;
import com.example.entity.UserInfo;
import com.example.service.MessageService;
import com.example.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static cn.hutool.core.date.DateUtil.now;

@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private UserInfoService userInfoService;


    @Override
    public void packUser(Message message) {
        Integer receiverId = message.getReceiverId();
        Integer senderId = message.getSenderId();
        System.out.println(receiverId);
        System.out.println(senderId);
        UserInfo receiver = this.userInfoService.findById(Long.valueOf(receiverId));
        if (receiver == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "接受方不存在");
        }
        UserInfo sender = this.userInfoService.findById(Long.valueOf(senderId));
        if (sender == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "发送方不存在");
        }
        message.setReceiver(receiver);
        message.setSender(sender);
        Integer level = sender.getLevel();
        if (level == 1){
            message.setSenderName("admin");
        }else if (level == 3){
            message.setSenderName("consumer");
        }
    }

    //获取消息列表
    public List<Message> getByUserId(Message message){
        Integer senderId = message.getSenderId();
        Integer receiverId = message.getReceiverId();
        List<Message> all = messageMapper.getByUserId(senderId, receiverId);
        for(Message m : all){
            packUser(m);
        }
        return all;
    }

    //发送消息
    @Override
    public void deliver(Message message) {
        message.setTimestamp(now());
        int i = this.messageMapper.insertSelective(message);
        if (i == 0) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "添加失败");
        }
    }


}